//
//  CLIndexViewController.m
//  chanlin
//
//  Created by Ryan on 14-11-3.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "CLIndexViewController.h"
#import "ChannelControllerDataSource.h"
#import "CLIndexModel.h"
#import "IFCoreDataManager.h"
#import "NSObject+sagittarius.h"
#import "CLList.h"
#import "CLList+Oper.h"
#import "IFIndexCell.h"
#import "CLGloble.h"
#import "IfengOrderStore.h"
#import "CLSlidersViewController.h"
#import "CLPushAnimatedRight.h"
#import "CLDocViewController.h"
#import "IFIndexFocusCell.h"
#import "IFIndexIconCell.h"
#import "IFIndexSlidesCell.h"
#import "CLComentDataModel.h"
#import "CLTopicViewController.h"
#import "CLVideoViewController.h"
#import "IFIndexClassCell.h"
#import "CLSubViewController.h"
#import "ReadDocHistory.h"
#import "EColumn.h"
#import "CLSearchViewController.h"
#import "CLLiveViewController.h"
#import "IFIndexAudioCell.h"
#import "CLPictorialCell.h"
#import "CLPictorialFocusCell.h"
#import "CLWebVeiwController.h"

@interface CLIndexViewController()
@property (nonatomic,strong) NSDictionary *categroyDic;
@property (nonatomic,unsafe_unretained) int pageNum;
@property (nonatomic,unsafe_unretained)BOOL isCurrent;

@property (nonatomic,strong) UISearchBar *listSearchBar;
@end

@implementation CLIndexViewController

- (instancetype)init{
    self=[super init];
    if(self){
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;

    }
    return self;
}


- (void)viewDidLoad{
    [super viewDidLoad];
   // [self.tableView hiddenBottom:YES];
    //self.view.backgroundColor=[UIColor orangeColor];
    
    [self createSearchBtn];
}

- (void)createSearchBtn {
    
    UIButton *searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, GlobleWidth, 44.0)];
    searchBtn.backgroundColor = [UIColor clearColor];
    [searchBtn addTarget:self action:@selector(goForwardSearchView) forControlEvents:UIControlEventTouchUpInside];
    
    _listSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, GlobleWidth, 44.0)];

    _listSearchBar.backgroundColor = RGB(0xf8, 0xf8, 0xf8);
        _listSearchBar.tintColor = RGB(0xf5, 0x43, 0x43);
        _listSearchBar.barTintColor = RGB(0xf5, 0x43, 0x43);
    
    NSArray *subviewContainer = ((UIView *)_listSearchBar.subviews[0]).subviews;//_listSearchBar.subviews;//
    for (UIView *sub in subviewContainer) {
        if ([sub isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            sub.alpha = 0.f;
        }
        
        if ([sub isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
            sub.layer.borderWidth = 0.5f;
            
            sub.backgroundColor = [UIColor clearColor];
            sub.layer.borderColor = RGB(0xe0, 0xe0, 0xe0).CGColor;
            
                if([sub isKindOfClass:[UITextField class]]){
                    ((UITextField *)sub).textColor = RGB(0xc9, 0xc9, 0xc9);
                    ((UITextField *)sub).textAlignment = NSTextAlignmentLeft;
                        ((UITextField *)sub).tintColor = RGB(0xc9, 0xc9, 0xc9);
                        ((UITextField *)sub).placeholder = @"新闻搜索";
                }
        }
    }
    
      self.tableView.tableHeaderView = _listSearchBar;
    [_listSearchBar addSubview:searchBtn];
    
}

-(void)goForwardSearchView{
    
    CLSearchViewController *collect=[CLSearchViewController new];
    [[CLPushAnimatedRight sharedInstance] pushController:collect];
}

- (void)updateControllerWithIsCurrent:(BOOL)isCurrent{
    
   self.isCurrent=isCurrent;

    
}

- (void)updateControllerWithDataSource:(ChannelControllerDataSource *)datasource{
    [self.tableView resetBottomMoreViewAutoLoadTimes:0];
    [self.tableView stopHeadLoadingNoAnimated];
    self.isCurrent=datasource.isCurrentView;
    NSDictionary *dic=[[[IfengOrderStore sharedInstance] getOrderedMenuItem] sgrGetDictionaryForIndex:(int)datasource.index];
    [self setNewsCategory:dic];
    
}

//-(void)jTableViewStartHeadLoading:(JTableView *)tableView{
//    self.pageNum=1;
//    __weak typeof(self) me=self;
//    
//    [[CLIndexModel sharedInstance] getmagzineList:self.categroyDic
//                                          uiBlock:^(BOOL success, id responseObj, NSString *message) {
//                                              if(success){
//                                            [me.tableView stopHeadLoading];
//                        
//                                            }else{
//                                                [[CLGloble sharedInstance] showTieAlertMessage:@"加载失败"
//                                                    subMessage:message];
//                                                                }
//
//        
//    
//    }];
//}

-(void)jTableViewStartHeadLoading:(JTableView *)tableView{
    self.pageNum=1;
    __weak typeof(self) me=self;
    [[CLIndexModel sharedInstance] getListWithCategroy:self.categroyDic
                                              withPage:self.pageNum
     \
                                              lastList:nil
                                               uiBlock:^(BOOL success, id responseObj, NSString *message) {
                                                   if(success){
                                                       [me.tableView stopHeadLoading];
                                                       
                                                       if(me.listSearchBar){
                                                           [me.tableView setContentOffset:CGPointMake(0, 44.f)];
                                                       }
                                                       
                                                   }else{
                                                       [[CLGloble sharedInstance] showTieAlertMessage:@"加载失败"
                                                                                           subMessage:message];
                                                   }
                                               }];
}

- (void)jTableViewStartBottomMoreLoading:(JTableView *)tableView{
    __weak typeof(self) me=self;
    [[CLIndexModel sharedInstance] getListWithCategroy:self.categroyDic
                                              withPage:self.pageNum+1
                                              lastList:self.fetch.fetchedObjects.lastObject
                                               uiBlock:^(BOOL success, id responseObj, NSString *message) {
                                                   if(success){
                                                       me.pageNum++;
                                                       [me.tableView stopBottomMoreWithScuessLoading];
                                                   }else{
                                                       [me.tableView stopBottomMoreWithNothingLoading];
                                                   }
                                               }];
}

- (void)setNewsCategory:(NSDictionary *)dic{
    self.categroyDic=dic;
    if(!dic)return;
    [[CLIndexModel sharedInstance].pageNums setObject:@(self.pageNum) forKey:[dic sgrGetStringForKey:@"channelId"]];
    NSNumber *numb=[[CLIndexModel sharedInstance].pageNums sgrGetNumberForKey:[dic sgrGetStringForKey:@"channelId"]];
    self.pageNum=numb?[numb intValue]:1;
    
    
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"sort" ascending:YES];
    NSFetchRequest *req = [[NSFetchRequest alloc] initWithEntityName:@"CLList"];
    req.predicate = [NSPredicate predicateWithFormat:@"category=%@", [dic sgrGetStringForKey:@"channelId"]];
    req.sortDescriptors = @[sort];
    self.fetch = [[NSFetchedResultsController alloc] initWithFetchRequest:req
                                                     managedObjectContext:[IFCoreDataManager sharedInstance].mainMoc
                                                       sectionNameKeyPath:nil
                                                                cacheName:nil];
    self.fetch.delegate=self;
    [self.fetch performFetch:nil];
    
    self.tableView.refrashType = JTableViewRefrashType_RefrashAuto;
    [self doReflashWithAnimation:self.isCurrent];


    if([self isViewLoaded])
        [self reloadTable];
    
}



- (void)doReflashWithAnimation:(BOOL)isAnimation{
    self.isShouldReloadTableView=YES;
    if(isAnimation){
        [self.tableView becameHeadReflashLoading];
    }else{
        [self.tableView becameHeadReflashLoadingNoAnimation];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CLList *newsList=[self.fetch objectAtIndexPath:indexPath];
    return newsList.cHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CLList *list=[self.fetch objectAtIndexPath:indexPath];
    IFIndexCell *cell=[self cellForStyle:list.style tableView:tableView indexpath:indexPath];
    [cell loadData:list];
    [cell setPlayVideo:list.link==CLList_video];
    if(list.link!=CLList_sub)
        [cell setIsRead:[[ReadDocHistory shareInstance] check:list.itemId]];
    
  
    
    cell.indexPath=indexPath;
    cell.delegate=self;
    
    return cell;
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    EColumn *colum=[self.fetch objectAtIndexPath:[NSIndexPath indexPathForRow:section inSection:0]];
//    if(_isStrNULL(colum.name)) return nil;
//    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, GlobleWidth, colum.cHeight)];
//    view.backgroundColor=[UIColor whiteColor];
//    
//    UILabel *label=[[UILabel alloc] init];
//    label.backgroundColor=[UIColor whiteColor];
//    label.textColor=RGB(0x84,0x92,0xa7);
//    label.font=[UIFont fontWithName:@"Helvetica-Bold" size:17.f];
//    label.text=colum.name;
//    label.frame=CGRectMake(13.f, 0.f, GlobleWidth-30.f, colum.cHeight);
//    [view addSubview:label];
//    
//    CALayer *cellSeperatorImgView=[CALayer layer];
//     cellSeperatorImgView.frame=CGRectMake(0, 0.f, GlobleWidth, 0.5f);
//     cellSeperatorImgView.backgroundColor=RGB(0xe0, 0xe0, 0xde).CGColor;
//    [view.layer addSublayer:cellSeperatorImgView];
//    
//    
//    cellSeperatorImgView=[CALayer layer];
//    cellSeperatorImgView.frame=CGRectMake(0, colum.cHeight-0.5f, GlobleWidth, 0.5f);
//    cellSeperatorImgView.backgroundColor=RGB(0xe0, 0xe0, 0xde).CGColor;
//    [view.layer addSublayer:cellSeperatorImgView];
//
//    
//    return view;
//    
//}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    EColumn *colum=[self.fetch objectAtIndexPath:[NSIndexPath indexPathForRow:section inSection:0]];
//    if(_isStrNULL(colum.name)) return 0;
//    return colum.cHeight;
//}


//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    id<NSFetchedResultsSectionInfo> sectionInfo=[[self.fetch sections] objectAtIndex:0];
//    return [sectionInfo numberOfObjects];
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//   EColumn *colum=[self.fetch objectAtIndexPath:[NSIndexPath indexPathForRow:section inSection:0]];
//    return [colum.book count];
//}

- (IFIndexCell *)cellForStyle:(int)style tableView:(UITableView *)tableView indexpath:(NSIndexPath *)indexPath{
    if(style==CLList_style_focus){
        NSString *cellID=[NSString stringWithFormat:@"IFIndexFocusCell%@%@",@(indexPath.section),@(indexPath.row)];
       // static NSString *cellID=str;
        IFIndexFocusCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[IFIndexFocusCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            __weak typeof(self) me=self;
            cell._blkTapResponse=^(CLList *indexList,int index,NSIndexPath *indexPath){
                CLList *list=[indexList.focus sgrGetType:[CLList class] forIndex:index];
                [me clickOnList:list];
            };
        }
        return cell;
    }else if (style==CLList_style_doc_img){
        static NSString *cellID=@"IFIndexIconCell";
        IFIndexIconCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[IFIndexIconCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        return cell;
    }else if(style==CLList_style_doc){
        static NSString *cellID=@"IFIndexTitleCell";
        IFIndexTitleCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[IFIndexTitleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        return cell;
    }else if(style==CLList_style_slide){
        static NSString *cellID=@"IFIndexSlidesCell";
        IFIndexSlidesCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[IFIndexSlidesCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        return cell;
    }else if(style==CLList_style_topic_sub){
        static NSString *cellID=@"IFIndexClassCell";
        IFIndexClassCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[IFIndexClassCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        return cell;
    }else if(style==CLList_style_audio){
        static NSString *cellID=@"IFIndexAudioCell";
        IFIndexAudioCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[IFIndexAudioCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        return cell;

    }else if(style==CLList_style_huabao){
        static NSString *cellID=@"IFIndexHuaBao";
        CLPictorialCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[CLPictorialCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        return cell;
        
    }else if(style==CLList_style_huabaoFocus){
        
        NSString *cellID=[NSString stringWithFormat:@"IFIndexHuaBaoFocus%@%@",@(indexPath.section),@(indexPath.row)];
        
        CLPictorialFocusCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[CLPictorialFocusCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            __weak typeof(self) me=self;
            cell._blkTapResponse=^(CLList *indexList,int index,NSIndexPath *indexPath){
                CLList *list=[indexList.focus sgrGetType:[CLList class] forIndex:index];
                [me clickOnList:list];
            };
        }
        return cell;
        
    }
    
    return [[IFIndexCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"IFIndexCell"];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CLList *list=[self.fetch objectAtIndexPath:indexPath];
    [self clickOnList:list];
    IFIndexCell *cell=(IFIndexCell *)[tableView cellForRowAtIndexPath:indexPath];
    if(list.link!=CLList_sub)
    [cell setIsRead:YES];
   }

- (void)didSelect:(NSIndexPath *)indexPath{
    CLList *list=[self.fetch objectAtIndexPath:indexPath];
    [self clickOnList:list];
    IFIndexCell *cell=(IFIndexCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    if(list.link!=CLList_sub)
        [cell setIsRead:YES];
}

- (void)clickOnList:(CLList *)list{
    if(list.link==CLList_sliders){
        CLSlidersViewController *slider=[CLSlidersViewController new];
        slider.itemId=list.itemId;
        [[CLPushAnimatedRight sharedInstance] pushController:slider];
        
    }else if(list.link==CLList_doc){
        CLDocViewController *doc=[CLDocViewController new];
        doc.itemId=list.itemId;
       // doc.itemId=@"4973";
        [[CLPushAnimatedRight sharedInstance] pushController:doc];
    }else if(list.link==CLList_topic){
        CLTopicViewController *topic=[CLTopicViewController new];
        topic.title=list.title;
        topic.itemId=list.itemId;
       
        [[CLPushAnimatedRight sharedInstance] pushController:topic];
    }else if(list.link==CLList_video){
               CLVideoViewController *video=[CLVideoViewController new];
        video.itemId=list.itemId;
        [[CLPushAnimatedRight sharedInstance] pushController:video];
    }else if(list.link==CLList_sub){
        CLSubViewController *sub=[CLSubViewController new];
        sub.itemId=list.classId;
        sub.objectiveId=list.objectID;
        sub.channel=self.categroyDic;
        //[sub loadData:list];
        [[CLPushAnimatedRight sharedInstance] pushController:sub];
    }else if(list.link==CLList_audio){
        CLDocViewController *doc=[CLDocViewController new];
        doc.isAudio=YES;
        doc.itemId=list.itemId;
        [[CLPushAnimatedRight sharedInstance] pushController:doc];
    }else if(list.link==CLList_live){
        CLLiveViewController *live=[CLLiveViewController new];
        
        live.itemId=list.itemId;
        [[CLPushAnimatedRight sharedInstance] pushController:live];
        return;

    
    }else if(list.link==CLList_web){
        CLWebVeiwController *web = [CLWebVeiwController new];
        
        web.itemId=list.url;
        [[CLPushAnimatedRight sharedInstance] pushController:web];
        return;
        
    }else{
        [[CLGloble sharedInstance] showAlertWithTitle:@"提示"
                                              message:@"请升级新版本app，支持此功能"
                                                block:nil
                                    cancelButtonTitle:@"确定" button1:nil button2:nil];
    }

}



@end
